<template>
  <div class="system-configuration">
    <h2>系统配置</h2>
    
    <div class="tabs">
      <button 
        :class="['tab-btn', { active: activeTab === 'ageGroup' }]" 
        @click="activeTab = 'ageGroup'"
      >
        年龄分组配置
      </button>
      <button 
        :class="['tab-btn', { active: activeTab === 'popupConfig' }]" 
        @click="activeTab = 'popupConfig'"
      >
        弹窗配置
      </button>
      <button 
        :class="['tab-btn', { active: activeTab === 'announcements' }]" 
        @click="activeTab = 'announcements'"
      >
        公告设置
      </button>
    </div>
    
    <div class="tab-content">
      <!-- 年龄分组配置 -->
      <div v-if="activeTab === 'ageGroup'" class="age-group-config">
        <div class="config-header">
          <h3>年龄分组配置</h3>
          <button 
        @click="showAddAgeGroupModal = true" 
        class="add-btn"
        :disabled="loading"
      >
        新增分组
      </button>
        </div>
        
        <div class="age-group-list">
          <table class="config-table">
            <thead>
              <tr>
                <th>分组ID</th>
                <th>分组名称</th>
                <th>最小年龄</th>
                <th>最大年龄</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="loading">
                <td colspan="5" class="loading-message">加载中...</td>
              </tr>
              <template v-else>
                <tr v-for="group in ageGroups" :key="group.id">
                  <td>{{ group.id }}</td>
                  <td>{{ group.name }}</td>
                  <td>{{ group.minAge }}</td>
                  <td>{{ group.maxAge === 999 ? '无上限' : group.maxAge }}</td>
                  <td>
                    <div class="action-buttons">
                      <button 
                        @click="editAgeGroup(group)" 
                        class="edit-btn"
                        :disabled="loading"
                      >
                        编辑
                      </button>
                      <button 
                        @click="deleteAgeGroup(group.id)" 
                        class="delete-btn"
                        :disabled="group.id === 1 || loading"
                      >
                        删除
                      </button>
                    </div>
                  </td>
                </tr>
                <tr v-if="ageGroups.length === 0">
                  <td colspan="5" class="empty-message">暂无年龄分组数据</td>
                </tr>
              </template>
            </tbody>
          </table>
        </div>
        
        <!-- 新增年龄分组弹窗 -->
        <div v-if="showAddAgeGroupModal" class="modal-overlay" @click.self="closeAddAgeGroupModal">
          <div class="modal-content">
            <div class="modal-header">
              <h4>新增年龄分组</h4>
              <button @click="closeAddAgeGroupModal" class="close-btn">&times;</button>
            </div>
            <div class="modal-body">
              <div class="form-group">
                <label for="newGroupName">分组名称 <span class="required">*</span></label>
                <input 
                  type="text" 
                  id="newGroupName" 
                  v-model="newAgeGroup.name"
                  placeholder="如：18-30岁"
                />
              </div>
              <div class="form-group">
                <label for="newMinAge">最小年龄 <span class="required">*</span></label>
                <input 
                  type="number" 
                  id="newMinAge" 
                  v-model.number="newAgeGroup.minAge"
                  placeholder="请输入最小年龄"
                  min="1"
                />
              </div>
              <div class="form-group">
                <label for="newMaxAge">最大年龄 <span class="required">*</span></label>
                <input 
                  type="number" 
                  id="newMaxAge" 
                  v-model.number="newAgeGroup.maxAge"
                  placeholder="请输入最大年龄，无上限请输入999"
                  min="1"
                />
              </div>
              <div v-if="ageGroupError" class="error-message">
                {{ ageGroupError }}
              </div>
            </div>
            <div class="modal-footer">
              <button 
                @click="saveNewAgeGroup" 
                class="save-btn"
                :disabled="loading"
              >
                {{ loading ? '保存中...' : '保存' }}
              </button>
              <button 
                @click="closeAddAgeGroupModal" 
                class="cancel-btn"
                :disabled="loading"
              >
                取消
              </button>
            </div>
          </div>
        </div>
        
        <!-- 编辑年龄分组弹窗 -->
        <div v-if="showEditAgeGroupModal" class="modal-overlay" @click.self="closeEditAgeGroupModal">
          <div class="modal-content">
            <div class="modal-header">
              <h4>编辑年龄分组</h4>
              <button @click="closeEditAgeGroupModal" class="close-btn">&times;</button>
            </div>
            <div class="modal-body">
              <div class="form-group">
                <label for="editGroupName">分组名称 <span class="required">*</span></label>
                <input 
                  type="text" 
                  id="editGroupName" 
                  v-model="editAgeGroupForm.name"
                  placeholder="如：18-30岁"
                />
              </div>
              <div class="form-group">
                <label for="editMinAge">最小年龄 <span class="required">*</span></label>
                <input 
                  type="number" 
                  id="editMinAge" 
                  v-model.number="editAgeGroupForm.minAge"
                  placeholder="请输入最小年龄"
                  min="1"
                />
              </div>
              <div class="form-group">
                <label for="editMaxAge">最大年龄 <span class="required">*</span></label>
                <input 
                  type="number" 
                  id="editMaxAge" 
                  v-model.number="editAgeGroupForm.maxAge"
                  placeholder="请输入最大年龄，无上限请输入999"
                  min="1"
                />
              </div>
              <div v-if="editAgeGroupError" class="error-message">
                {{ editAgeGroupError }}
              </div>
            </div>
            <div class="modal-footer">
              <button 
                @click="updateAgeGroup" 
                class="save-btn"
                :disabled="loading"
              >
                {{ loading ? '更新中...' : '更新' }}
              </button>
              <button 
                @click="closeEditAgeGroupModal" 
                class="cancel-btn"
                :disabled="loading"
              >
                取消
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 弹窗配置 -->
      <div v-else-if="activeTab === 'popupConfig'" class="popup-config">
        <div class="config-header">
          <h3>预测须知弹窗配置</h3>
          <div v-if="popupConfig.updateTime" class="update-time">
            最后更新时间：{{ new Date(popupConfig.updateTime).toLocaleString('zh-CN') }}
          </div>
        </div>
        
        <div class="config-form">
          <div class="form-group">
            <label for="countdownTime">倒计时时长(秒) <span class="required">*</span></label>
            <input 
              type="number" 
              id="countdownTime" 
              v-model.number="popupConfig.countdownTime"
              min="1"
              max="60"
              placeholder="请输入倒计时时长(1-60秒)"
            />
            <div class="help-text">倒计时结束前，关闭按钮将处于禁用状态</div>
          </div>
          
          <div class="form-group">
            <label for="popupContent">弹窗内容 <span class="required">*</span></label>
            <textarea 
              id="popupContent" 
              v-model="popupConfig.content"
              rows="5"
              placeholder="请输入弹窗提示内容"
            ></textarea>
          </div>
          
          <div class="form-group">
            <label>弹窗预览</label>
            <div class="popup-preview">
              <div class="popup-preview-header">预测须知</div>
              <div class="popup-preview-body">
                {{ popupConfig.content || '请输入弹窗内容以预览' }}
              </div>
              <div class="popup-preview-footer">
                <span>倒计时：{{ popupConfig.countdownTime || 30 }}秒</span>
                <button disabled class="disabled-close-btn">关闭</button>
              </div>
            </div>
          </div>
          
          <div v-if="popupConfigError" class="error-message">
            {{ popupConfigError }}
          </div>
          
          <div class="form-actions">
            <button @click="savePopupConfig" class="save-btn" :disabled="loading">
              {{ loading ? '保存中...' : '保存配置' }}
            </button>
            <button @click="resetPopupConfig" class="reset-btn" :disabled="loading">
              重置
            </button>
          </div>
        </div>
      </div>
      
      <!-- 公告设置 -->
      <div v-else-if="activeTab === 'announcements'" class="announcements-config">
        <div class="config-header">
          <h3>系统公告管理</h3>
          <button @click="showAddAnnouncementModal = true" class="add-btn" :disabled="loading">
            发布公告
          </button>
        </div>
        
        <div class="filter-section">
          <div class="filter-controls">
            <div class="filter-group">
              <label for="announcementTitle">公告标题</label>
              <input 
                type="text" 
                id="announcementTitle" 
                v-model="announcementFilters.title"
                placeholder="请输入公告标题"
              />
            </div>
            
            <div class="filter-group">
              <label for="publishStatus">发布状态</label>
              <select v-model="announcementFilters.publishStatus" id="publishStatus">
                <option value="all">全部状态</option>
                <option value="1">已发布</option>
                <option value="2">草稿</option>
                <option value="3">已撤回</option>
              </select>
            </div>
            
            <div class="filter-group">
              <label for="targetType">目标用户</label>
              <select v-model="announcementFilters.targetType" id="targetType">
                <option value="all">全部用户</option>
                <option value="0">全部用户</option>
                <option value="1">仅普通用户</option>
                <option value="2">仅疾控统计员</option>
              </select>
            </div>
            
            <button @click="searchAnnouncements" class="search-btn" :disabled="loading">搜索</button>
            <button @click="resetAnnouncementFilters" class="reset-btn" :disabled="loading">重置</button>
          </div>
        </div>
        
        <div class="announcement-list">
          <table class="config-table">
            <thead>
              <tr>
                <th>公告ID</th>
                <th>公告标题</th>
                <th>目标用户</th>
                <th>发布状态</th>
                <th>置顶</th>
                <th>查看次数</th>
                <th>
                  <div>
                    发布日期
                    <button 
                      @click="toggleSortDirection" 
                      :disabled="loading"
                      style="background: none; border: none; cursor: pointer; font-size: 14px; padding: 0 4px; color: #666;"
                    >
                      {{ sortDirection === 'desc' ? '↓' : '↑' }}
                    </button>
                  </div>
                </th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="loading">
                <td colspan="8" class="loading-message">加载中...</td>
              </tr>
              <template v-else>
                <tr v-for="(announcement, index) in filteredAnnouncements" :key="announcement.id">
                  <td>{{ index + 1 }}</td>
                  <td>{{ announcement.title }}</td>
                  <td>
                    {{ 
                      announcement.targetType === 0 ? '全部用户' : 
                      announcement.targetType === 1 ? '仅普通用户' : 
                      '仅疾控统计员'
                    }}
                  </td>
                  <td>
                    <span class="status-badge" :class="getPublishStatusClass(announcement.publishStatus)">
                      {{ 
                        announcement.publishStatus === 1 ? '已发布' : 
                        announcement.publishStatus === 2 ? '草稿' : 
                        '已撤回'
                      }}
                    </span>
                  </td>
                  <td>
                    <span class="top-badge" :class="announcement.isTop ? 'is-top' : ''">
                      {{ announcement.isTop ? '是' : '否' }}
                    </span>
                  </td>
                  <td>{{ announcement.viewCount }}</td>
                  <td>{{ announcement.publishDate }}</td>
                  <td>
                    <div class="action-buttons">
                      <button @click="editAnnouncement(announcement)" class="edit-btn" :disabled="loading">
                        编辑
                      </button>
                      <button 
                        @click="toggleAnnouncementStatus(announcement)"
                        class="toggle-btn"
                        :disabled="loading"
                      >
                        {{ 
                          announcement.publishStatus === 1 ? '撤回' : 
                          announcement.publishStatus === 2 ? '发布' : 
                          '重新发布'
                        }}
                      </button>
                      <button 
                        @click="deleteAnnouncement(announcement.id)" 
                        class="delete-btn"
                        :disabled="loading"
                      >
                        删除
                      </button>
                    </div>
                  </td>
                </tr>
                <tr v-if="filteredAnnouncements.length === 0">
                  <td colspan="8" class="empty-message">暂无公告数据</td>
                </tr>
              </template>
            </tbody>
          </table>
        </div>
        
        <!-- 新增公告弹窗 -->
        <div v-if="showAddAnnouncementModal" class="modal-overlay" @click.self="closeAddAnnouncementModal">
          <div class="modal-content announcement-modal">
            <div class="modal-header">
              <h4>发布公告</h4>
              <button @click="closeAddAnnouncementModal" class="close-btn">&times;</button>
            </div>
            <div class="modal-body">
              <div class="form-group">
                <label for="newAnnouncementTitle">公告标题 <span class="required">*</span></label>
                <input 
                  type="text" 
                  id="newAnnouncementTitle" 
                  v-model="newAnnouncement.title"
                  placeholder="请输入公告标题"
                  maxlength="50"
                />
                <div class="help-text">{{ newAnnouncement.title.length }}/50</div>
              </div>
              <div class="form-group">
                <label for="newAnnouncementContent">公告内容 <span class="required">*</span></label>
                <textarea 
                  id="newAnnouncementContent" 
                  v-model="newAnnouncement.content"
                  rows="10"
                  placeholder="请输入公告内容"
                  maxlength="1000"
                ></textarea>
                <div class="help-text">{{ newAnnouncement.content.length }}/1000</div>
              </div>
              <div class="form-row">
                <div class="form-group">
                  <label for="newAnnouncementTargetType">目标用户 <span class="required">*</span></label>
                  <select id="newAnnouncementTargetType" v-model="newAnnouncement.targetType">
                    <option value="0">全部用户</option>
                    <option value="1">仅普通用户</option>
                    <option value="2">仅疾控统计员</option>
                  </select>
                </div>
                
                <div class="form-group">
                  <label for="newAnnouncementPublishStatus">发布状态 <span class="required">*</span></label>
                  <select id="newAnnouncementPublishStatus" v-model="newAnnouncement.publishStatus">
                    <option value="1">已发布</option>
                    <option value="2">草稿</option>
                  </select>
                </div>
                
                <div class="form-group">
                  <label for="newAnnouncementIsTop">是否置顶</label>
                  <select id="newAnnouncementIsTop" v-model="newAnnouncement.isTop">
                    <option value="0">否</option>
                    <option value="1">是</option>
                  </select>
                </div>
              </div>
              
              <div class="form-row">
                <div class="form-group">
                  <label for="newAnnouncementStartTime">开始显示时间</label>
                  <input 
                    type="date" 
                    id="newAnnouncementStartTime" 
                    v-model="newAnnouncement.startTime"
                  />
                </div>
                
                <div class="form-group">
                  <label for="newAnnouncementEndTime">结束显示时间</label>
                  <input 
                    type="date" 
                    id="newAnnouncementEndTime" 
                    v-model="newAnnouncement.endTime"
                  />
                </div>
              </div>
              <div v-if="announcementError" class="error-message">
                {{ announcementError }}
              </div>
              
              <div class="form-group">
                <label>公告预览</label>
                <div class="announcement-preview">
                  <div class="announcement-preview-header">
                    {{ newAnnouncement.title || '请输入公告标题' }}
                  </div>
                  <div class="announcement-preview-body">
                    {{ newAnnouncement.content || '请输入公告内容' }}
                  </div>
                  <div class="announcement-preview-footer">
                    {{ new Date().toLocaleDateString('zh-CN') }}
                  </div>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <button @click="saveNewAnnouncement" class="save-btn" :disabled="loading">{{ loading ? '发布中...' : '发布' }}</button>
              <button @click="closeAddAnnouncementModal" class="cancel-btn" :disabled="loading">取消</button>
            </div>
          </div>
        </div>
        
        <!-- 编辑公告弹窗 -->
        <div v-if="showEditAnnouncementModal" class="modal-overlay" @click.self="closeEditAnnouncementModal">
          <div class="modal-content announcement-modal">
            <div class="modal-header">
              <h4>编辑公告</h4>
              <button @click="closeEditAnnouncementModal" class="close-btn">&times;</button>
            </div>
            <div class="modal-body">
              <div class="form-group">
                <label for="editAnnouncementTitle">公告标题 <span class="required">*</span></label>
                <input 
                  type="text" 
                  id="editAnnouncementTitle" 
                  v-model="editAnnouncementForm.title"
                  placeholder="请输入公告标题"
                  maxlength="50"
                />
                <div class="help-text">{{ editAnnouncementForm.title.length }}/50</div>
              </div>
              <div class="form-group">
                <label for="editAnnouncementContent">公告内容 <span class="required">*</span></label>
                <textarea 
                  id="editAnnouncementContent" 
                  v-model="editAnnouncementForm.content"
                  rows="10"
                  placeholder="请输入公告内容"
                  maxlength="1000"
                ></textarea>
                <div class="help-text">{{ editAnnouncementForm.content.length }}/1000</div>
              </div>
              <div class="form-row">
                <div class="form-group">
                  <label for="editAnnouncementTargetType">目标用户 <span class="required">*</span></label>
                  <select id="editAnnouncementTargetType" v-model="editAnnouncementForm.targetType">
                    <option value="0">全部用户</option>
                    <option value="1">仅普通用户</option>
                    <option value="2">仅疾控统计员</option>
                  </select>
                </div>
                
                <div class="form-group">
                  <label for="editAnnouncementPublishStatus">发布状态 <span class="required">*</span></label>
                  <select id="editAnnouncementPublishStatus" v-model="editAnnouncementForm.publishStatus">
                    <option value="1">已发布</option>
                    <option value="2">草稿</option>
                    <option value="3">已撤回</option>
                  </select>
                </div>
                
                <div class="form-group">
                  <label for="editAnnouncementIsTop">是否置顶</label>
                  <select id="editAnnouncementIsTop" v-model="editAnnouncementForm.isTop">
                    <option value="0">否</option>
                    <option value="1">是</option>
                  </select>
                </div>
              </div>
              
              <div class="form-row">
                <div class="form-group">
                  <label for="editAnnouncementStartTime">开始显示时间</label>
                  <input 
                    type="date" 
                    id="editAnnouncementStartTime" 
                    v-model="editAnnouncementForm.startTime"
                  />
                </div>
                
                <div class="form-group">
                  <label for="editAnnouncementEndTime">结束显示时间</label>
                  <input 
                    type="date" 
                    id="editAnnouncementEndTime" 
                    v-model="editAnnouncementForm.endTime"
                  />
                </div>
              </div>
              <div v-if="editAnnouncementError" class="error-message">
                {{ editAnnouncementError }}
              </div>
              
              <div class="form-group">
                <label>公告预览</label>
                <div class="announcement-preview">
                  <div class="announcement-preview-header">
                    {{ editAnnouncementForm.title || '请输入公告标题' }}
                  </div>
                  <div class="announcement-preview-body">
                    {{ editAnnouncementForm.content || '请输入公告内容' }}
                  </div>
                  <div class="announcement-preview-footer">
                    {{ announcementPublishDate }}
                  </div>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <button @click="updateAnnouncement" class="save-btn" :disabled="loading">{{ loading ? '保存中...' : '保存' }}</button>
              <button @click="closeEditAnnouncementModal" class="cancel-btn" :disabled="loading">取消</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import api from '@/utils/axiosConfig.js'

export default {
  name: 'SystemConfiguration',
  setup() {
    const activeTab = ref('ageGroup')
    const showAddAgeGroupModal = ref(false)
    const showEditAgeGroupModal = ref(false)
    const ageGroupError = ref('')
    const editAgeGroupError = ref('')
    const popupConfigError = ref('')
    const editingAgeGroupId = ref(null)
    const loading = ref(false)
    
    // 公告相关状态
    const announcements = ref([])
    
    // 从后端获取所有公告
    const fetchAnnouncements = async () => {
      try {
        loading.value = true
        const response = await api.get('/sysNotice/getAll')
        
        // 检查响应数据是否为数组
        if (Array.isArray(response.data)) {
          // 转换后端数据格式为前端需要的格式
          announcements.value = response.data.map(notice => ({
            id: notice.noticeId || 0,
            title: notice.title || '',
            content: notice.content || '',
            publishDate: notice.createTime ? new Date(notice.createTime).toISOString().split('T')[0] : new Date().toISOString().split('T')[0],
            publishStatus: notice.publishStatus || 3, // 默认已撤回状态
            targetType: notice.targetType !== undefined ? notice.targetType : 0, // 默认全部用户
            isTop: notice.isTop !== undefined ? notice.isTop : 0, // 默认不置顶
            startTime: notice.startTime,
            endTime: notice.endTime,
            viewCount: notice.viewCount || 0,
            updateTime: notice.updateTime,
            publisherId: notice.publisherId || 10 // 默认发布人ID
          }))
        } else {
          console.error('获取公告失败: 数据不是数组', response.data)
          announcements.value = []
        }
      } catch (error) {
        console.error('获取公告失败:', error)
        alert('获取公告数据失败，请刷新页面重试')
        announcements.value = []
      } finally {
        loading.value = false
      }
    }
    
    const showAddAnnouncementModal = ref(false)
    const showEditAnnouncementModal = ref(false)
    const announcementError = ref('')
    const editAnnouncementError = ref('')
    const editingAnnouncementId = ref(null)
    const announcementPublishDate = ref('')
    
    const announcementFilters = reactive({
      title: '',
      publishStatus: 'all',
      targetType: 'all'
    })
    
    const newAnnouncement = reactive({
      title: '',
      content: '',
      publishStatus: 1, // 默认已发布
      targetType: 0,    // 默认全部用户
      isTop: 0,         // 默认不置顶
      startTime: '',    // 开始时间
      endTime: ''       // 结束时间
    })
    
    const editAnnouncementForm = reactive({
      title: '',
      content: '',
      publishStatus: 1,
      targetType: 0,
      isTop: 0,
      startTime: '',
      endTime: ''
    })
    
    // 年龄分组数据
    const ageGroups = ref([])
    
    // 从后端获取所有年龄分组
    const fetchAgeGroups = async () => {
      try {
        loading.value = true
        const response = await api.get('/age-group/all')
        
        // 检查响应数据是否为数组
        if (Array.isArray(response.data)) {
          // 转换后端数据格式为前端需要的格式
          ageGroups.value = response.data.map(group => ({
            id: group.ageGroupId,
            name: group.groupName,
            minAge: group.minAge,
            maxAge: group.maxAge,
            sort: group.sort,
            createTime: group.createTime,
            updateTime: group.updateTime
          }))
        } else if (response.data && response.data.length !== undefined) {
          // 处理可能的包装对象，比如 {"data": [...]} 格式
          const dataArray = response.data.data || response.data
          if (Array.isArray(dataArray)) {
            ageGroups.value = dataArray.map(group => ({
              id: group.ageGroupId,
              name: group.groupName,
              minAge: group.minAge,
              maxAge: group.maxAge,
              sort: group.sort,
              createTime: group.createTime,
              updateTime: group.updateTime
            }))
          } else {
            console.error('获取年龄分组失败: 数据格式不正确', response.data)
            ageGroups.value = []
          }
        } else {
          console.error('获取年龄分组失败: 数据不是数组', response.data)
          ageGroups.value = []
        }
      } catch (error) {
        console.error('获取年龄分组失败:', error)
        alert('获取年龄分组数据失败，请刷新页面重试')
        ageGroups.value = []
      } finally {
        loading.value = false
      }
    }
    
    // 初始弹窗配置
    const popupConfig = reactive({
      configId: 1,
      countdownTime: 30,
      content: '本预测基于您的血压、胆固醇等指标计算，结果仅供参考，不能替代医学诊断。建议每年进行一次专业体检。',
      updateTime: null
    })
    
    // 原始弹窗配置（用于重置）
    const originalPopupConfig = reactive({ ...popupConfig })
    
    // 从后端获取弹窗配置
    const fetchPopupConfig = async () => {
      try {
        loading.value = true
        // 由于数据库中配置ID默认为1，所以直接获取ID为1的配置
        const response = await api.get('/popup-config/1')
        
        if (response.data) {
          const config = response.data
          popupConfig.configId = config.configId || 1
          popupConfig.countdownTime = config.countdownSeconds || 30
          popupConfig.content = config.popupContent || ''
          popupConfig.updateTime = config.updateTime || new Date()
          
          // 更新原始配置用于重置
          Object.assign(originalPopupConfig, popupConfig)
        }
      } catch (error) {
        console.error('获取弹窗配置失败:', error)
        // 如果获取失败，可以使用默认配置
        console.log('使用默认弹窗配置')
      } finally {
        loading.value = false
      }
    }
    
    const newAgeGroup = reactive({
      name: '',
      minAge: null,
      maxAge: null
    })
    
    const editAgeGroupForm = reactive({
      name: '',
      minAge: null,
      maxAge: null
    })
    
    // 页面加载时获取数据
    onMounted(() => {
      fetchAgeGroups()
      fetchPopupConfig()
      fetchAnnouncements()
    })
    
    // 验证年龄分组
    const validateAgeGroup = (group) => {
      if (!group.name.trim()) {
        return '请输入分组名称'
      }
      if (!group.minAge || group.minAge < 1) {
        return '请输入有效的最小年龄'
      }
      if (!group.maxAge || group.maxAge < 1) {
        return '请输入有效的最大年龄'
      }
      if (group.minAge >= group.maxAge && group.maxAge !== 999) {
        return '最小年龄必须小于最大年龄'
      }
      
      // 检查年龄区间是否重叠
      for (let i = 0; i < ageGroups.value.length; i++) {
        const existingGroup = ageGroups.value[i]
        // 跳过当前编辑的分组
        if (editingAgeGroupId.value && existingGroup.id === editingAgeGroupId.value) {
          continue
        }
        
        // 检查重叠
        const newMin = group.minAge
        const newMax = group.maxAge === 999 ? 999 : group.maxAge
        const existingMin = existingGroup.minAge
        const existingMax = existingGroup.maxAge === 999 ? 999 : existingGroup.maxAge
        
        if (
          (newMin >= existingMin && newMin <= existingMax) ||
          (newMax >= existingMin && newMax <= existingMax) ||
          (newMin <= existingMin && newMax >= existingMax)
        ) {
          return `年龄区间与"${existingGroup.name}"重叠`
        }
      }
      
      return ''
    }
    
    const closeAddAgeGroupModal = () => {
      showAddAgeGroupModal.value = false
      ageGroupError.value = ''
      newAgeGroup.name = ''
      newAgeGroup.minAge = null
      newAgeGroup.maxAge = null
    }
    
    const saveNewAgeGroup = async () => {
      ageGroupError.value = validateAgeGroup(newAgeGroup)
      if (ageGroupError.value) {
        return
      }
      
      try {
        loading.value = true
        // 转换为后端需要的格式
        const backendAgeGroup = {
          groupName: newAgeGroup.name,
          minAge: newAgeGroup.minAge,
          maxAge: newAgeGroup.maxAge,
          sort: 0 // 默认排序
        }
        
        const response = await api.post('/age-group', backendAgeGroup)
        // 检查响应，后端返回boolean类型
        if (response.data === true) {
          alert('年龄分组添加成功！')
          closeAddAgeGroupModal()
          fetchAgeGroups() // 重新获取数据
        } else {
          console.error('添加年龄分组失败:', response.data)
          alert('年龄分组添加失败')
        }
      } catch (error) {
        console.error('添加年龄分组失败:', error)
        alert('添加年龄分组失败，请重试')
      } finally {
        loading.value = false
      }
    }
    
    const editAgeGroup = (group) => {
      editingAgeGroupId.value = group.id
      editAgeGroupForm.name = group.name
      editAgeGroupForm.minAge = group.minAge
      editAgeGroupForm.maxAge = group.maxAge
      showEditAgeGroupModal.value = true
    }
    
    const closeEditAgeGroupModal = () => {
      showEditAgeGroupModal.value = false
      editAgeGroupError.value = ''
      editingAgeGroupId.value = null
    }
    
    const updateAgeGroup = async () => {
      editAgeGroupError.value = validateAgeGroup(editAgeGroupForm)
      if (editAgeGroupError.value) {
        return
      }
      
      try {
        loading.value = true
        // 获取当前编辑分组的排序值，如果不存在则使用默认值
        const currentGroup = ageGroups.value.find(g => g.id === editingAgeGroupId.value)
        const sortValue = currentGroup ? currentGroup.sort : 0
        
        // 转换为后端需要的格式
        const backendAgeGroup = {
          ageGroupId: editingAgeGroupId.value,
          groupName: editAgeGroupForm.name,
          minAge: editAgeGroupForm.minAge,
          maxAge: editAgeGroupForm.maxAge,
          sort: sortValue // 添加sort字段
        }
        
        const response = await api.put('/age-group', backendAgeGroup)
        // 检查响应，后端返回boolean类型
        if (response.data === true) {
          alert('年龄分组更新成功！')
          closeEditAgeGroupModal()
          fetchAgeGroups() // 重新获取数据
        } else {
          console.error('更新年龄分组失败:', response.data)
          alert('年龄分组更新失败')
        }
      } catch (error) {
        console.error('更新年龄分组失败:', error)
        alert('更新年龄分组失败，请重试')
      } finally {
        loading.value = false
      }
    }
    
    const deleteAgeGroup = async (groupId) => {
      if (groupId === 1) {
        alert('默认分组不能删除！')
        return
      }
      
      if (confirm('确定要删除该年龄分组吗？删除后将无法恢复！')) {
        try {
          loading.value = true
          const response = await api.delete(`/age-group/${groupId}`)
          // 检查响应，后端返回boolean类型
          if (response.data === true) {
            alert('年龄分组已删除！')
            fetchAgeGroups() // 重新获取数据
          } else {
            console.error('删除年龄分组失败:', response.data)
            alert('年龄分组删除失败')
          }
        } catch (error) {
          console.error('删除年龄分组失败:', error)
          alert('删除年龄分组失败，请重试')
        } finally {
          loading.value = false
        }
      }
    }
    
    // 验证弹窗配置
    const validatePopupConfig = () => {
      if (!popupConfig.countdownTime || popupConfig.countdownTime < 1 || popupConfig.countdownTime > 60) {
        return '倒计时时长必须在1-60秒之间'
      }
      if (!popupConfig.content.trim()) {
        return '请输入弹窗内容'
      }
      if (popupConfig.content.length > 500) {
        return '弹窗内容不能超过500个字符'
      }
      return ''
    }
    
    const savePopupConfig = async () => {
      popupConfigError.value = validatePopupConfig()
      if (popupConfigError.value) {
        return
      }
      
      try {
        loading.value = true
        // 转换为后端需要的格式
        const backendConfig = {
          configId: popupConfig.configId,
          popupContent: popupConfig.content,
          countdownSeconds: popupConfig.countdownTime
        }
        
        const response = await api.put('/popup-config', backendConfig)
        // 检查响应，后端返回boolean类型
        if (response.data === true) {
          alert('弹窗配置保存成功！')
          // 重新获取最新配置，包括更新时间
          fetchPopupConfig()
        } else {
          console.error('保存弹窗配置失败:', response.data)
          alert('弹窗配置保存失败')
        }
      } catch (error) {
        console.error('保存弹窗配置失败:', error)
        alert('弹窗配置保存失败，请重试')
      } finally {
        loading.value = false
      }
    }
    
    const resetPopupConfig = () => {
      popupConfig.configId = originalPopupConfig.configId
      popupConfig.countdownTime = originalPopupConfig.countdownTime
      popupConfig.content = originalPopupConfig.content
      popupConfig.updateTime = originalPopupConfig.updateTime
      popupConfigError.value = ''
    }
    
    // 排序方向，默认降序（newest first）
    const sortDirection = ref('desc')
    
    // 切换排序方向
    const toggleSortDirection = () => {
      sortDirection.value = sortDirection.value === 'desc' ? 'asc' : 'desc'
    }
    
    // 筛选后的公告列表
    const filteredAnnouncements = computed(() => {
      let result = [...announcements.value]
      
      // 按标题筛选 - 确保即使标题为null或undefined也能正确处理
      if (announcementFilters.title && announcementFilters.title.trim()) {
        const searchTerm = announcementFilters.title.toLowerCase().trim();
        result = result.filter(a => 
          a.title && a.title.toLowerCase().includes(searchTerm)
        )
      }
      
      // 按发布状态筛选 - 确保parseInt处理正确
      if (announcementFilters.publishStatus && announcementFilters.publishStatus !== 'all') {
        const statusValue = parseInt(announcementFilters.publishStatus);
        result = result.filter(a => a.publishStatus === statusValue)
      }
      
      // 按目标类型筛选 - 确保parseInt处理正确
      if (announcementFilters.targetType && announcementFilters.targetType !== 'all') {
        const targetValue = parseInt(announcementFilters.targetType);
        result = result.filter(a => a.targetType === targetValue)
      }
      
      // 先按置顶状态排序，再按发布日期排序
      result.sort((a, b) => {
        if (b.isTop !== a.isTop) {
          return b.isTop - a.isTop
        }
        // 根据排序方向决定升序还是降序
        const dateComparison = new Date(b.publishDate) - new Date(a.publishDate)
        return sortDirection.value === 'desc' ? dateComparison : -dateComparison
      })
      
      return result
    })
    
    // 搜索公告
    const searchAnnouncements = () => {
      console.log('搜索公告:', announcementFilters)
      // 实际搜索逻辑已在computed中实现，这里可以添加额外的搜索相关逻辑
    }
    
    // 获取发布状态对应的CSS类名
    const getPublishStatusClass = (status) => {
      switch(status) {
        case 1: return 'status-published'
        case 2: return 'status-draft'
        case 3: return 'status-withdrawn'
        default: return ''
      }
    }
    
    // 重置公告筛选
    const resetAnnouncementFilters = () => {
      announcementFilters.title = ''
      announcementFilters.publishStatus = 'all'
      announcementFilters.targetType = 'all'
    }
    
    // 验证公告
    const validateAnnouncement = (announcement) => {
      if (!announcement.title.trim()) {
        return '请输入公告标题'
      }
      if (announcement.title.length > 50) {
        return '公告标题不能超过50个字符'
      }
      if (!announcement.content.trim()) {
        return '请输入公告内容'
      }
      if (announcement.content.length > 1000) {
        return '公告内容不能超过1000个字符'
      }
      return ''
    }
    
    // 关闭新增公告弹窗
    const closeAddAnnouncementModal = () => {
      showAddAnnouncementModal.value = false
      announcementError.value = ''
      newAnnouncement.title = ''
      newAnnouncement.content = ''
      newAnnouncement.publishStatus = 1
      newAnnouncement.targetType = 0
      newAnnouncement.isTop = 0
      newAnnouncement.startTime = ''
      newAnnouncement.endTime = ''
    }
    
    // 保存新增公告
    const saveNewAnnouncement = async () => {
      announcementError.value = validateAnnouncement(newAnnouncement)
      if (announcementError.value) {
        return
      }
      
      try {
        loading.value = true
        // 转换为后端需要的格式
        const backendNotice = {
          title: newAnnouncement.title,
          content: newAnnouncement.content,
          targetType: parseInt(newAnnouncement.targetType),
          publishStatus: parseInt(newAnnouncement.publishStatus),
          isTop: parseInt(newAnnouncement.isTop),
          startTime: newAnnouncement.startTime ? new Date(newAnnouncement.startTime) : null,
          endTime: newAnnouncement.endTime ? new Date(newAnnouncement.endTime) : null,
          publisherId: 10 // 默认发布人ID，实际应用中应从登录用户获取
        }
        
        const response = await api.post('/sysNotice/add', backendNotice)
        
        // 检查响应，后端返回影响行数
        if (response.data > 0) {
          alert('公告发布成功！')
          closeAddAnnouncementModal()
          fetchAnnouncements() // 重新获取数据
        } else {
          console.error('发布公告失败:', response.data)
          alert('公告发布失败')
        }
      } catch (error) {
        console.error('发布公告失败:', error)
        alert('公告发布失败，请重试')
      } finally {
        loading.value = false
      }
    }
    
    // 编辑公告
    const editAnnouncement = (announcement) => {
      editingAnnouncementId.value = announcement.id
      editAnnouncementForm.title = announcement.title
      editAnnouncementForm.content = announcement.content
      editAnnouncementForm.publishStatus = announcement.publishStatus
      editAnnouncementForm.targetType = announcement.targetType
      editAnnouncementForm.isTop = announcement.isTop
      editAnnouncementForm.startTime = announcement.startTime ? new Date(announcement.startTime).toISOString().split('T')[0] : ''
      editAnnouncementForm.endTime = announcement.endTime ? new Date(announcement.endTime).toISOString().split('T')[0] : ''
      announcementPublishDate.value = announcement.publishDate
      showEditAnnouncementModal.value = true
    }
    
    // 关闭编辑公告弹窗
    const closeEditAnnouncementModal = () => {
      showEditAnnouncementModal.value = false
      editAnnouncementError.value = ''
      editingAnnouncementId.value = null
    }
    
    // 更新公告
    const updateAnnouncement = async () => {
      editAnnouncementError.value = validateAnnouncement(editAnnouncementForm)
      if (editAnnouncementError.value) {
        return
      }
      
      // 验证editingAnnouncementId是否有效
      if (!editingAnnouncementId.value || isNaN(parseInt(editingAnnouncementId.value))) {
        console.error('无效的公告ID:', editingAnnouncementId.value)
        alert('更新失败：无效的公告ID')
        return
      }
      
      try {
        loading.value = true
        // 转换为后端需要的格式，确保noticeId为数字类型
        const noticeIdNum = parseInt(editingAnnouncementId.value)
        const backendNotice = {
          noticeId: noticeIdNum,
          title: editAnnouncementForm.title.trim(),
          content: editAnnouncementForm.content.trim(),
          targetType: parseInt(editAnnouncementForm.targetType),
          publishStatus: parseInt(editAnnouncementForm.publishStatus),
          isTop: parseInt(editAnnouncementForm.isTop),
          // 添加publisherId字段，后端需要这个字段且不能为空
          publisherId: editAnnouncementForm.publisherId || 10, // 使用表单中的publisherId或默认值10
          // 添加viewCount字段，后端需要这个字段且不能为空
          viewCount: editAnnouncementForm.viewCount || 0, // 使用表单中的浏览次数或默认值0
          startTime: editAnnouncementForm.startTime ? new Date(editAnnouncementForm.startTime) : null,
          endTime: editAnnouncementForm.endTime ? new Date(editAnnouncementForm.endTime) : null
        }
        
        const response = await api.post('/sysNotice/update', backendNotice)
        
        // 检查响应，后端返回影响行数
        if (response.data && response.data > 0) {
          alert('公告更新成功！')
          closeEditAnnouncementModal()
          fetchAnnouncements() // 重新获取数据
        } else {
          console.error('更新公告失败，影响行数:', response.data)
          alert(`更新公告失败: ${response.data || '未知错误'}`)
        }
      } catch (error) {
        console.error('更新公告异常:', error)
        console.error('错误详情:', error.response || error)
        alert(`更新公告失败: ${error.message || '网络或服务器错误'}`)
      } finally {
        loading.value = false
      }
    }
    
    // 更新公告状态
    const toggleAnnouncementStatus = async (announcement) => {
      let newStatus, actionText
      
      if (announcement.publishStatus === 1) { // 已发布 -> 已撤回
        newStatus = 3
        actionText = '撤回'
      } else if (announcement.publishStatus === 2) { // 草稿 -> 已发布
        newStatus = 1
        actionText = '发布'
      } else if (announcement.publishStatus === 3) { // 已撤回 -> 已发布
        newStatus = 1
        actionText = '重新发布'
      }
      
      if (confirm(`确定要${actionText}该公告吗？`)) {
        try {
          loading.value = true
          // 构建完整的公告对象，包含所有必要字段
          const noticeIdNum = parseInt(announcement.id)
          const backendNotice = {
            noticeId: noticeIdNum,
            publishStatus: newStatus,
            title: announcement.title,
            content: announcement.content,
            targetType: parseInt(announcement.targetType),
            isTop: parseInt(announcement.isTop),
            // 添加publisherId字段，后端需要这个字段且不能为空
            publisherId: announcement.publisherId || 10, // 使用公告原有的publisherId或默认值10
            // 添加viewCount字段，后端需要这个字段且不能为空
            viewCount: announcement.viewCount || 0, // 使用公告原有的浏览次数或默认值0
            // 保持原有的时间信息
            startTime: announcement.startTime ? new Date(announcement.startTime) : null,
            endTime: announcement.endTime ? new Date(announcement.endTime) : null
          }
          
          console.log('更新公告状态请求数据:', backendNotice)
          const response = await api.post('/sysNotice/update', backendNotice)
          
          if (response.data && response.data > 0) {
            alert(`公告已${actionText}！`)
            fetchAnnouncements() // 重新获取数据
          } else {
            const errorMsg = response.data || '未知错误'
            console.error('更新公告状态失败:', errorMsg)
            alert(`更新公告状态失败: ${errorMsg}`)
          }
        } catch (error) {
          console.error('更新公告状态失败:', error)
          console.error('错误详情:', error.response ? JSON.stringify(error.response.data) : error.message)
          const errorMsg = error.response?.data?.message || error.message || '服务器错误'
          alert(`更新公告状态失败: ${errorMsg}`)
        } finally {
          loading.value = false
        }
      }
    }
    
    // 删除公告
    const deleteAnnouncement = async (announcementId) => {
      if (confirm('确定要删除该公告吗？删除后将无法恢复！')) {
        try {
          loading.value = true
          // 确保传递的是数字类型的ID
          const id = parseInt(announcementId)
          const response = await api.delete(`/sysNotice/delete/${id}`)
          
          // 检查响应，后端返回影响行数
          if (response.data > 0) {
            alert('公告已删除！')
            fetchAnnouncements() // 重新获取数据
          } else {
            console.error('删除公告失败:', response.data)
            alert('公告删除失败')
          }
        } catch (error) {
          console.error('删除公告失败:', error)
          alert('删除公告失败，请重试')
        } finally {
          loading.value = false
        }
      }
    }
    
    return {
      activeTab,
      ageGroups,
      loading,
      popupConfig,
      showAddAgeGroupModal,
      showEditAgeGroupModal,
      newAgeGroup,
      editAgeGroupForm,
      ageGroupError,
      editAgeGroupError,
      popupConfigError,
      closeAddAgeGroupModal,
      saveNewAgeGroup,
      editAgeGroup,
      closeEditAgeGroupModal,
      updateAgeGroup,
      deleteAgeGroup,
      savePopupConfig,
      resetPopupConfig,
      // 公告相关
      announcements,
      filteredAnnouncements,
      announcementFilters,
      showAddAnnouncementModal,
      showEditAnnouncementModal,
      newAnnouncement,
      editAnnouncementForm,
      announcementError,
      editAnnouncementError,
      announcementPublishDate,
      searchAnnouncements,
      resetAnnouncementFilters,
      closeAddAnnouncementModal,
      saveNewAnnouncement,
      editAnnouncement,
      closeEditAnnouncementModal,
      updateAnnouncement,
      toggleAnnouncementStatus,
      deleteAnnouncement,
      getPublishStatusClass,
      // 排序相关
      sortDirection,
      toggleSortDirection
    }
  }
}
</script>

<style scoped>
.system-configuration {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

.system-configuration h2 {
  color: #333;
  margin-bottom: 20px;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.tab-btn {
  padding: 12px 24px;
  background: none;
  border: none;
  color: #909399;
  cursor: pointer;
  font-size: 16px;
  position: relative;
}

.tab-btn.active {
  color: #409eff;
}

.tab-btn.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #409eff;
}

.tab-content {
  padding: 10px 0;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.config-header h3 {
  color: #303133;
  margin: 0;
}

.add-btn {
  padding: 8px 20px;
  background-color: #67c23a;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.add-btn:hover {
  background-color: #85ce61;
}

.config-table {
  width: 100%;
  border-collapse: collapse;
}

.config-table th,
.config-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

.config-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.action-buttons button {
  padding: 4px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.loading-message {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.empty-message {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.edit-btn {
  background-color: #409eff;
  color: #fff;
}

.edit-btn:hover {
  background-color: #66b1ff;
}

.delete-btn {
  background-color: #f56c6c;
  color: #fff;
}

.delete-btn:hover:not(:disabled) {
  background-color: #f78989;
}

.delete-btn:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}

.toggle-btn {
  padding: 4px 12px;
  background-color: #e6a23c;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.toggle-btn:hover {
  background-color: #ebb563;
}

.empty-message {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.filter-controls {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  color: #606266;
  white-space: nowrap;
}

.filter-group input,
.filter-group select {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-width: 150px;
}

.search-btn {
  padding: 6px 20px;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.search-btn:hover {
  background-color: #66b1ff;
}

.config-form {
  max-width: 700px;
}

.form-group {
  margin-bottom: 25px;
}

.form-group label {
  display: block;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.required {
  color: #f56c6c;
}

.form-group input[type="text"],
.form-group input[type="number"],
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #409eff;
}

.help-text {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.popup-preview {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.popup-preview-header {
  background-color: #f5f7fa;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  font-weight: 500;
  color: #303133;
}

.popup-preview-body {
  padding: 20px;
  min-height: 100px;
  color: #606266;
  line-height: 1.6;
}

.popup-preview-footer {
  padding: 15px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #909399;
}

.disabled-close-btn {
  padding: 6px 16px;
  background-color: #f5f7fa;
  color: #c0c4cc;
  border: none;
  border-radius: 4px;
  cursor: not-allowed;
}

.form-actions {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.save-btn {
  padding: 8px 24px;
  background-color: #67c23a;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.save-btn:hover {
  background-color: #85ce61;
}

.reset-btn {
  padding: 8px 24px;
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}

.reset-btn:hover {
  color: #409eff;
  border-color: #c6e2ff;
}

/* 状态标签 */
.status-badge {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
}

.status-badge.active {
  background-color: #f0f9ff;
  color: #409eff;
}

.status-badge.inactive {
  background-color: #f5f7fa;
  color: #909399;
}

/* 公告发布状态样式 */
.status-badge.status-published {
  background-color: #f0f9ff;
  color: #409eff;
}

.status-badge.status-draft {
  background-color: #f4f4f5;
  color: #909399;
}

.status-badge.status-withdrawn {
  background-color: #fef0f0;
  color: #f56c6c;
}

/* 置顶徽章样式 */
.top-badge {
  padding: 2px 8px;
  background-color: #fef0f0;
  color: #f56c6c;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
  margin-left: 6px;
}

/* 表单行布局 */
.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 25px;
}

.form-row .form-group {
  flex: 1;
  margin-bottom: 0;
}

/* 公告管理表格样式 */
.announcement-table {
  width: 100%;
  border-collapse: collapse;
}

.announcement-table th, 
.announcement-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
  white-space: nowrap;
}

.announcement-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

/* 调整表格列宽度 */
.announcement-table th:nth-child(1),
.announcement-table td:nth-child(1) {
  width: 40%;
  white-space: normal;
  word-break: break-word;
}

.announcement-table th:nth-child(2),
.announcement-table td:nth-child(2) {
  width: 15%;
}

.announcement-table th:nth-child(3),
.announcement-table td:nth-child(3) {
  width: 15%;
}

.announcement-table th:nth-child(4),
.announcement-table td:nth-child(4) {
  width: 10%;
}

.announcement-table th:nth-child(5),
.announcement-table td:nth-child(5) {
  width: 10%;
}

.announcement-table th:nth-child(6),
.announcement-table td:nth-child(6) {
  width: 10%;
  text-align: center;
}

/* 公告预览样式 */
.announcement-preview {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  background-color: #fafafa;
}

.announcement-preview-header {
  background-color: #f5f7fa;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.announcement-preview-body {
  padding: 20px;
  min-height: 150px;
  color: #606266;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.announcement-preview-footer {
  padding: 10px 15px;
  border-top: 1px solid #ebeef5;
  text-align: right;
  color: #909399;
  font-size: 12px;
}

/* 公告弹窗样式 */
.announcement-modal {
  max-width: 700px;
  max-height: 90vh;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.15);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.error-message {
  color: #f56c6c;
  margin-top: 10px;
  padding: 10px;
  background-color: #fef0f0;
  border-radius: 4px;
  border-left: 3px solid #f56c6c;
  font-size: 14px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.2s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.modal-content {
  background-color: #fff;
  border-radius: 12px;
  width: 90%;
  max-width: 450px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  animation: modalSlideIn 0.3s ease-out;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h4 {
  color: #303133;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #909399;
  cursor: pointer;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background-color: #f5f7fa;
  color: #606266;
}

.modal-body {
  padding: 24px;
  max-height: calc(90vh - 140px);
  overflow-y: auto;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px 24px;
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;
  border-radius: 0 0 12px 12px;
}

/* 表单样式优化 */
.form-group {
  margin-bottom: 24px;
  position: relative;
}

.form-group label {
  display: block;
  color: #606266;
  margin-bottom: 10px;
  font-weight: 500;
  font-size: 14px;
}

.form-group input[type="text"],
.form-group input[type="number"],
.form-group input[type="date"],
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 10px 14px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
  background-color: #fff;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.form-group textarea {
  resize: vertical;
  min-height: 120px;
  font-family: inherit;
  line-height: 1.5;
}

.help-text {
  color: #909399;
  font-size: 12px;
  margin-top: 6px;
  text-align: right;
}

/* 表单行布局优化 */
.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.form-row .form-group {
  flex: 1;
  min-width: 160px;
  margin-bottom: 0;
}

/* 按钮样式优化 */
.save-btn {
  padding: 10px 28px;
  background-color: #67c23a;
  color: #fff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.save-btn:hover:not(:disabled) {
  background-color: #85ce61;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

.save-btn:active:not(:disabled) {
  transform: translateY(0);
}

.save-btn:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.cancel-btn {
  padding: 10px 28px;
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn:hover:not(:disabled) {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.cancel-btn:disabled {
  color: #c0c4cc;
  border-color: #ebeef5;
  background-color: #f5f7fa;
  cursor: not-allowed;
}

/* 公告预览样式增强 */
.announcement-preview {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.announcement-preview:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.announcement-preview-header {
  background-color: #f5f7fa;
  padding: 18px 20px;
  border-bottom: 1px solid #ebeef5;
  font-weight: 600;
  color: #303133;
  font-size: 16px;
  line-height: 1.5;
}

.announcement-preview-body {
  padding: 20px;
  min-height: 150px;
  color: #606266;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
  font-size: 14px;
}

.announcement-preview-footer {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
  color: #909399;
  font-size: 13px;
  background-color: #fafafa;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .modal-content {
    width: 95%;
    margin: 20px;
  }
  
  .announcement-modal {
    width: 95%;
    margin: 10px;
  }
  
  .form-row {
    flex-direction: column;
    gap: 24px;
  }
  
  .modal-body {
    padding: 20px;
    max-height: calc(90vh - 160px);
  }
  
  .modal-header,
  .modal-footer {
    padding-left: 20px;
    padding-right: 20px;
  }
  
  .modal-footer {
    flex-direction: column;
  }
  
  .save-btn,
  .cancel-btn {
    width: 100%;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tabs {
    flex-direction: column;
  }
  
  .tab-btn {
    text-align: left;
    border-bottom: 1px solid #ebeef5;
  }
  
  .tab-btn.active::after {
    left: 24px;
    width: 4px;
    height: 70%;
    bottom: 15%;
  }
  
  .filter-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-group {
    flex-direction: column;
    align-items: stretch;
    margin-bottom: 12px;
  }
  
  .filter-group input,
  .filter-group select {
    min-width: auto;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 6px;
  }
  
  .modal-content {
    width: 95%;
    margin: 20px;
  }
  
  .announcement-modal {
    width: 95%;
  }
}
</style>